import { useState } from "react";
import { useLazyGetUserQuery } from "../../api/users";
import { Box, Button, TextField, Typography } from "@mui/material";
import s from "./styles.module.scss";
import { UserCard } from "../UI/userCard";
import { Loader } from "../UI/loader";

export const SearchPage = () => {
  const [data, setData] = useState(null);
  const [text, setText] = useState("");
  const [getUser, { isLoading, isError }] = useLazyGetUserQuery();

  const onFindUser = async () => {
    try {
      const response = await getUser(text);
      setData(response.data);
    } catch (e) {
      alert(e);
    }
  };

  return (
    <Box className={s.search}>
      <Typography className={s.search__title}>Social Life</Typography>
      <Box>
        <TextField
          id="outlined-basic"
          label="Пользователь"
          variant="outlined"
          className={s.search__input}
          onChange={(e) => setText(e.target.value)}
        />
        <Button
          variant="contained"
          className={s.search__button}
          onClick={() => onFindUser()}
        >
          Найти
        </Button>
      </Box>

      <Box className={s.search__result}>
        {data ? (
          data.map((elem, key) => (
            <UserCard
              name={elem.name}
              key={key}
              username={elem.username}
              s={s}
            />
          ))
        ) : isLoading ? (
          <Loader width={"100px"} height={"100px"} />
        ) : null}
      </Box>
    </Box>
  );
};
